package org.hughie.sync;

import lombok.extern.slf4j.Slf4j;
import org.hughie.api.FundApisMapping;
import org.hughie.common.FundSyncType;
import org.hughie.http.IHttpInvoker;
import org.hughie.mapper.BaseInfoMapper;
import org.hughie.model.fmn.BaseFundInfoFMN;
import org.hughie.model.po.BaseFundInfoPO;
import org.hughie.model.po.BatchJob;
import org.hughie.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * @author hughie.cheng
 * @date 2024/3/1
 */
@Component
@Slf4j
public class FundBaseInfoTask implements FundSyncTask {

    @Autowired
    private BaseInfoMapper baseInfoMapper;
    @Autowired
    private IHttpInvoker invoker;
    @Qualifier("syncThreadExecutor")
    @Autowired
    private ExecutorService executor;

    @Override
    public String getTaskCode() {
        return FundSyncType.BASIC.getTaskName();
    }

    @Override
    public void sync(String fundCode) {
        BaseFundInfoFMN fmn = invoker.get(FundApisMapping.FUND_BASE_INFO, fundCode, TimeUtil.getCurrentMills());
        String lastDay = baseInfoMapper.getLastDay(fundCode);
        if (lastDay != null && fmn.getFSRQ().compareTo(lastDay) <= 0) {
            return;
        }
        BaseFundInfoPO fundInfoPO = fmn.coverToBaseFundInfoPO();
        log.info(fundInfoPO.toString());
        executor.submit(() -> baseInfoMapper.save(fundInfoPO));
    }

    @Override
    public void syncBatch(List<BatchJob> jobs) {
        baseInfoMapper.truncateTable();
        jobs.forEach(t -> sync(t.getFundCode()));
    }
}
